<template>
    <div>
        <el-dialog title="修改销售订单" v-model="props.visible" @close="handleClose" @open="handleOpen" width="70%">
            <!-- 表单数据 -->
            <el-form :model="props.order">
                <el-row :gutter="20">
                    <el-col :span="6">
                        <el-form-item label="订单名称">
                            <el-input v-model="props.order.salesOrderName" placeholder="请输入订单名称"></el-input>
                        </el-form-item>
                    </el-col>

                    <el-col :span="6">
                        <el-form-item label="客户编码" prop="customerCode">
                            <el-input v-model="props.order.customerCode" placeholder="请选择客户">
                                <template #append>
                                    <el-button type="primary" :icon="Search" @click="selectClient"></el-button>
                                </template>
                            </el-input>
                        </el-form-item>
                    </el-col>

                    <el-col :span="6">
                        <el-form-item label="订货日期">
                            <el-date-picker v-model="props.order.salesOrderDate" type="date" placeholder="订货日期"
                                value-format="YYYY-MM-DD HH:mm:ss" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="交货日期">
                            <el-date-picker v-model="props.order.deliveryDate" type="date" placeholder="交货日期"
                                value-format="YYYY-MM-DD HH:mm:ss" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="6">
                        <el-form-item label="订单类型">
                            <el-select v-model="props.order.orderType" placeholder="请选择订单类型">
                                <el-option label="客户订单" :value="0"></el-option>
                                <el-option label="备货订单" :value="1"></el-option>
                                <el-option label="样品订单" :value="2"></el-option>
                                <el-option label="退货订单" :value="3"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="24">
                        <el-form-item label="备注">
                            <el-input type="textarea" v-model="props.order.remark" placeholder="请输入内容"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <!-- 分割线 -->
            <el-row :gutter="20">
                <el-divider>
                    <span>销售订单产品列信息</span>
                </el-divider>
            </el-row>
            <!-- 按钮 -->
            <el-row :gutter="20">
                <el-button type="primary" plain :icon="Plus" @click="addItem">新增</el-button>
                <el-button type="danger" plain :icon="Delete" @click="deleteItem" :disabled="isDeleteRow">删除</el-button>
            </el-row>
            <!-- 表格 -->

            <el-table :data="props.order.salesOrderItems" style="width: 100%" @selection-change="handleSelectionChange">
                <el-table-column type="selection" :selectable="selectable" width="55" />
                <el-table-column label="序号" type="index" width="55" />
                <el-table-column label="产品编码" prop="productCode">
                    <template #default="scope">
                        <el-input v-model="scope.row.productCode" placeholder="请输入产品编码">
                            <template #append>
                                <el-button :icon="Search" @click="searchProduct(scope.$index, scope.row)" />
                            </template>
                        </el-input>
                    </template>
                </el-table-column>
                <el-table-column label="产品名称" prop="productName">
                    <template #default="scope">
                        <el-input v-model="scope.row.productName" placeholder="请输入产品名称"></el-input>
                    </template>
                </el-table-column>
                <el-table-column label="订货数量" prop="salesOrderQuantity">
                    <template #default="scope">
                        <el-input v-model="scope.row.salesOrderQuantity" placeholder="请输入订货数量"></el-input>
                    </template>
                </el-table-column>
                <el-table-column label="单价" prop="amount">
                    <template #default="scope">
                        <el-input v-model="scope.row.amount" placeholder="请输入单价"></el-input>
                    </template>
                </el-table-column>
                <el-table-column label="金额" prop="productTotalPrice">
                    <template #default="scope">
                        <el-input v-model="scope.row.productTotalPrice" placeholder="0" readonly disabled></el-input>
                    </template>
                </el-table-column>
            </el-table>

            <template #footer>
                <div class="dialog-footer">
                    <el-button v-if="props.order.status == 0" type="primary" @click="saveOrder">保存</el-button>
                    <el-button v-if="props.order.status == 0 " type="success" @click="identifyOrder">确定</el-button>
                    <el-button @click="handleClose">
                        取消
                    </el-button>
                </div>
            </template>

        </el-dialog>
        <SearchProduct :productVisible="productVisible" @productSelect="handleProductSelect" :index="updateIndex">
        </SearchProduct>
        <CustomerSelectionDialog :CustomerDialog="CustomerDialog" @close-dialog="closeCustomer" @rowDataA="getCustomer">
        </CustomerSelectionDialog>
    </div>
</template>

<script setup>
import { onMounted, ref, watch } from 'vue'
import SearchProduct from './SearchProduct.vue'
import { updateProduct } from '@/apis/index'
import { Plus, Delete, Search } from '@element-plus/icons-vue'
import CustomerSelectionDialog from '@/components/CustomerOrders/CustomerSelectionDialog.vue'
import { ElMessage } from 'element-plus'

const props = defineProps({
    visible: Boolean,
    order: Object
})
const emits = defineEmits(['closeUpdateDialog'])
const CustomerDialog = ref(false) //客户选择框
const form = ref({
    salesOrderId: null,
    salesOrderCode: null,
    salesOrderName: null,
    salesOrderDate: null,
    deliveryDate: null,
    orderType: null,
    remark: null,
    salesOrderItems: []
})
const isDeleteRow = ref(true); //是否删除行
const productVisible = ref(false); //产品选择弹窗
// 收集选中行的索引，用于删除选中行
const productIndex = ref([])
const updateIndex = ref(null) //选中行索引

//关闭修改弹窗
const handleClose = () => {
    emits('closeUpdateDialog')
}
const handleOpen = () => {
    // form.value = {...props.order}
    // console.log("数据")
    // console.log(form.value)
}
// 保存订单
const saveOrder = async () => {
    props.order.salesOrderItems = props.order.salesOrderItems.filter(item => item.productId != null)
    await updateProduct(props.order)
    ElMessage.success('保存成功')
    emits('closeUpdateDialog')
}
// 生产订单确认
const identifyOrder = async () => {
    props.order.salesOrderItems = props.order.salesOrderItems.filter(item => item.productId != null)
    if(!props.order.salesOrderItems.length > 0 ){
        ElMessage.error('请先添加产品')
        return
    }
    props.order.status = 1
    await updateProduct(props.order)
    ElMessage.success('生产订单已确认')
    emits('closeUpdateDialog')
}
//添加一个空对象
const addItem = () => {
    props.order.salesOrderItems.push(CreateItem())
}

//打开搜索产品弹窗
const searchProduct = (index, row) => {
    updateIndex.value = index
    productVisible.value = !productVisible.value;
}

// 处理选择事件
const handleSelectionChange = (val) => {
    isDeleteRow.value = !val.length;
    productIndex.value = val.map(item => item.index);
}
// 所有行都可以被选中
const selectable = () => true;

// 删除选中行数据
const deleteItem = () => {
    if (productIndex.value.length == props.order.salesOrderItems.length) {
        props.order.salesOrderItems = []
    } else {
        for (let i = 0; i < productIndex.value.length; i++) {
            selectProduct.value.splice(productIndex.value[i] - 1, 1)
        }
    }
    productIndex.value = []
}
// 处理选择的产品
const handleProductSelect = (ProductRow, index) => {
    productVisible.value = false;
    if (ProductRow.productName) {
        const { materialProductCode, productName, materialNo } = ProductRow;
        props.order.salesOrderItems[index].productCode = materialProductCode
        props.order.salesOrderItems[index].productName = productName
        props.order.salesOrderItems[index].productId = materialNo
    }
    console.log(props.order)
}
function CreateItem() {
    return {
        index: props.order.salesOrderItems.length + 1,
        productId: null,
        productCode: null,
        productName: null,
        salesOrderQuantity: 0,
        amount: 0,
    }
}



//监听数量和单价变化，计算金额
watch(
    () => props.order.salesOrderItems.map(product => ({
        productQuantity: product.salesOrderQuantity,
        productPrice: product.amount
    })),
    (newValues) => {
        newValues.forEach((value, index) => {
            props.order.salesOrderItems[index].productTotalPrice = value.productQuantity * value.productPrice;
        });
    },
    { deep: true }
);

//打开客户选择框
const selectClient = () => {
    CustomerDialog.value = true
}

//关闭客户选择框
const closeCustomer = () => {
    CustomerDialog.value = false
}

//获取到选择的客户信息
const getCustomer = (row) => {
    const { customerId, customerCode } = { ...row }
    props.order.customerId = customerId
    props.order.customerCode = customerCode
}

</script>

<style scoped></style>
